<template>
  <wd-form ref="dynamicForm" :model="formData">
    <wd-cell-group>
      <!-- 动态渲染表单组件 -->
      <view v-for="(item, index) in formFields" :key="index">
        <view v-if="item.type === 'Switch'">
          <view class="flex flex-items-center p3 justify-between">
            <wd-switch
              v-model="formData[item.field]"
              :label="item.label"
              :prop="item.field"
              active-color="#13ce66"
              inactive-color="#f00"
            />
          </view>
        </view>
        <view v-if="item.type === 'Text'">
          <wd-input
            v-model="formData[item.field]"
            :label="item.label"
            :prop="item.field"
            placeholder="请输入内容"
          />
        </view>

        <view v-if="item.type === 'Date'">
          <wd-datetime-picker
            type="date"
            v-model="formData[item.field]"
            :label="item.label"
            :prop="item.field"
            placeholder="请选择日期"
          />
        </view>
      </view>
      <wd-cell title-width="0px">
        <view class="footer">
          <wd-button size="small" @click="executeBtn(true)">提交</wd-button>
          <wd-button type="error" size="small" @click="executeBtn(false)">回退</wd-button>
        </view>
      </wd-cell>
    </wd-cell-group>
  </wd-form>
</template>

<script lang="ts" setup>
import { flowinstanceExecute } from '@/service/index/flow'
import { reactive, ref } from 'vue'
import { useMessage } from 'wot-design-uni/components/wd-message-box'
import { useToast } from 'wot-design-uni/components/wd-toast'
const message = useMessage()

// const { success: showSuccess } = useToast()
const dynamicForm = ref()
const toast = useToast()
let instance = null
let eventChannel = null

// 表单绑定对象
const formData = ref({})
// 存储label信息
const labelsInfo = ref([])
// 表单项
const formFields = ref([
  {
    label: '',
    type: '',
    field: '',
    value: '',
    props: '',
  },
])
// 存储实例所有信息
const flowInstanceInfo = ref({})

/**
 * @description: 初始化
 * @return {*}
 */
onMounted(() => {
  instance = getCurrentInstance().proxy
  eventChannel = instance.getOpenerEventChannel()
  eventChannel.on(
    'acceptDataFromOpenerPage',
    function ({ formDataInfo, formLabels, formFieldInfo }) {
      formFields.value = formFieldInfo
      flowInstanceInfo.value = formDataInfo
      labelsInfo.value = formLabels.map((v) => {
        const { Category, headerName } = v
        return {
          Category,
          headerName,
        }
      })
      formData.value = formFieldInfo.reduce((acc, item) => {
        acc[item.field] = item.value
        return acc
      }, {})
    },
  )
})

/**
 * @description: 提交/回退
 * @param {*} flag
 * @return {*}
 */
const executeBtn = (flag: boolean) => {
  const data = flowInstanceInfo.value as any
  const {
    FlowTemplateNodeFormID,
    FlowTemplateNodeID,
    Id,
    CurrentNodeId,
    InstanceId,
    FinishNode,
    ...rest
  } = data
  if (flag && FinishNode) {
    // return message('当前流程信息已完成，不可再次提交!', { type: "warning" })
  }
  message
    .confirm({
      msg: flag ? '确认提交？' : '确认回退？',
      title: '提示',
    })
    .then(() => {
      // 获取执行的列
      const canEditKeys = Object.keys(data?.cellInfo || {}).filter((v) => {
        return data.cellInfo?.[v]?.CanEdit
      })
      // 获取可提交的字段当前
      // console.log(data);
      const params = {
        // UpdateUser: useUserStoreHook().username,
        Status: flag,
        FlowTemplateNodeId: CurrentNodeId,
        FlowInstanceId: InstanceId,
        NodeForms: canEditKeys.map((val) => {
          let Val = formData.value[val] || ''
          // 特殊处理Date 事件格式
          if (labelsInfo.value.find((v) => v.headerName === val)?.Category === 'Date') {
            const date = new Date(Val)
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0') // 补零
            const day = String(date.getDate()).padStart(2, '0') // 补零
            Val = `${year}-${month}-${day}`
          }
          return {
            Id: data?.cellInfo?.[val]?.Id,
            Label: val,
            Val,
          }
        }),
      }
      flowinstanceExecute(params).then((rsp) => {
        if (rsp.IsSuccess) {
          toast.success(flag ? '提交成功！' : '回退成功！')
          // 返回查询界面并刷新
          setTimeout(() => {
            uni.navigateBack()
            // eventChannel.emit('refershEvent', { data: 'data from test page for someEvent' })
          }, 800)
        } else {
          toast.error(rsp.ErrorMsg)
        }
      })
    })
    .catch(() => {
      // console.log('点击了取消按钮')
    })
}
</script>
<style scoped lang="scss">
.page {
  height: 100vh;
  background-color: $uni-bg-color-hover;
  .mt12 {
    margin-top: 12rpx;
  }
  .mb12 {
    margin-bottom: 12rpx;
  }

  .search-type {
    position: relative;
    height: 30px;
    line-height: 30px;
    padding: 0 8px 0 16px;
    ::v-deep(.wd-popover__menu) {
      margin-left: 130rpx;
      height: 200rpx !important;
      overflow: scroll !important;
    }
  }
  .search-type::after {
    position: absolute;
    content: '';
    width: 1px;
    right: 0;
    top: 5px;
    bottom: 5px;
    background: rgba(0, 0, 0, 0.25);
  }
  .search-type {
    :deep(.icon-arrow) {
      display: inline-block;
      font-size: 20px;
      vertical-align: middle;
    }
  }
}
.footer {
  text-align: end;
  :deep(.wd-button) {
    &:not(:last-child) {
      margin-right: 12px;
    }
  }
}
</style>
